package com.yjtc.cbg.chatdemo.app;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.avos.avoscloud.AVOSCloud;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.im.v2.AVIMClient;
import com.avos.avoscloud.im.v2.AVIMConversation;
import com.avos.avoscloud.im.v2.AVIMException;
import com.avos.avoscloud.im.v2.AVIMMessage;
import com.avos.avoscloud.im.v2.AVIMMessageHandler;
import com.avos.avoscloud.im.v2.AVIMMessageManager;
import com.avos.avoscloud.im.v2.callback.AVIMClientCallback;
import com.avos.avoscloud.im.v2.messages.AVIMTextMessage;

/**
 * Created by chen on 2016/5/27.
 */
public class MyApplication extends Application {

    private String toUser;

    public String getToUser() {
        return toUser;
    }

    public void setToUser(String toUser) {
        this.toUser = toUser;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    private String token;

    public AVUser getmUser() {
        return mUser;
    }

    public void setmUser(AVUser mUser) {
        this.mUser = mUser;
    }

    private static MyApplication mApplication;

    private AVUser mUser;

    private static Context mContetx;

    @Override
    public void onCreate() {
        super.onCreate();
        mContetx = getApplicationContext();
        mApplication = this;
        // 初始化参数依次为 this, AppId, AppKey
        AVOSCloud.initialize(this, "CNejiSwmGDwC9tpJL21IXUag-gzGzoHsz", "0iX4qfHklnHgS69yTR6brMLc");
        // 启用北美节点
        AVOSCloud.useAVCloudCN();

        //注册默认的消息处理逻辑
        AVIMMessageManager.registerDefaultMessageHandler(new CustomMessageHandler());
    }

    public static MyApplication getInstance() {
        return mApplication;
    }


    public static class CustomMessageHandler extends AVIMMessageHandler {
        //接收到消息后的处理逻辑
        @Override
        public void onMessage(AVIMMessage message, AVIMConversation conversation, AVIMClient client){
            if(message instanceof AVIMTextMessage){
              //  Log.d("Tom & Jerry",((AVIMTextMessage)message).getText());
                //mContext.
                Intent intent = new Intent();
                intent.setAction("com.chenbaige.recieve_msg");
                intent.putExtra("msg", ((AVIMTextMessage) message).getText());
                mContetx.sendBroadcast(intent);
            }
        }

        public void onMessageReceipt(AVIMMessage message,AVIMConversation conversation,AVIMClient client){

        }
    }


    public void jerryReceiveMsgFromTom(){
        //Jerry登录
        AVIMClient jerry = AVIMClient.getInstance("Jerry");
        jerry.open(new AVIMClientCallback(){

            @Override
            public void done(AVIMClient client,AVIMException e){
                if(e==null){
                    //...//登录成功后的逻辑
                }
            }
        });
    }
}
